<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-2xl mx-auto bg-white rounded-2xl shadow-xl p-6">
      <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">
        添加课程
      </h2>

      <form @submit.prevent="handleSubmit" class="space-y-4">
        <div>
          <label class="block text-gray-700 mb-2 font-medium">课程名称</label>
          <input
            v-model="form.title"
            type="text"
            required
            placeholder="请输入课程名称"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>

        <!-- <div>
          <label class="block text-gray-700 mb-2 font-medium">所属类别</label>
          <select 
            v-model="form.categoryId"
            required
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          >
            <option value="">请选择课程类别</option>
            <option 
              v-for="category in categories" 
              :key="category.id"
              :value="category.id"
            >
              {{ category.title }}
            </option>
          </select>
        </div> -->

        <div>
          <label class="block text-gray-700 mb-2 font-medium"
            >上课老师姓名</label
          >
          <input
            v-model="form.teachername"
            type="text"
            placeholder="请输入上课老师姓名（可选）"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>

        <div>
          <label class="block text-gray-700 mb-2 font-medium">开始时间</label>
          <input
            v-model="form.startTime"
            type="datetime-local"
            required
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>
        <div>
          <label class="block text-gray-700 mb-2 font-medium">结束时间</label>
          <input
            v-model="form.endTime"
            type="datetime-local"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>

        <div>
          <label class="block text-gray-700 mb-2 font-medium">课程介绍</label>
          <textarea
            v-model="form.body"
            rows="5"
            required
            placeholder="请输入课程详细描述"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          ></textarea>
        </div>

        <div>
          <label class="block text-gray-700 mb-2 font-medium">课程图片</label>
          <input
            v-model="form.picPaths"
            type="text"
            placeholder="请输入课程图片链接（可选）"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>

        <button
          type="submit"
          class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg transition-colors shadow-lg shadow-blue-200/50 mt-6"
          :disabled="submitting"
        >
          {{ submitting ? "提交中..." : "提交" }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "../store/auth";
import api from "../services/api";

const router = useRouter();
const auth = useAuthStore();
const submitting = ref(false);
const categories = ref([]);
const form = ref({
  title: "",
  categoryId: "",
  teachername: "", // 对应数据库字段
  startTime: "",
  endTime: "", // 新增结束时间
  body: "", // 对应数据库字段，原为description
  picPaths: "", // 新增课程图片
});

// 加载课程类别
const loadCategories = async () => {
  try {
    const res = await api.getCategories();
    if (res && res.data.errno === 0) {
      categories.value = res.data.data;
    }
  } catch (error) {
    console.error("加载课程类别失败:", error);
    // 添加模拟类别数据，确保表单能正常显示
    categories.value = [
      { id: 1, title: "计算机科学" },
      { id: 2, title: "数学与统计" },
      { id: 3, title: "外语学习" },
      { id: 4, title: "艺术设计" },
    ];
  }
};

// 处理表单提交
const handleSubmit = async () => {
  // 验证用户是否已登录
  if (!auth.isLoggedIn || !auth.userId) {
    alert("请先登录后再添加课程");
    router.push("/login");
    return;
  }

  // 表单验证
  if (!form.value.title.trim()) {
    alert("课程名称不能为空");
    return;
  }
  // if (!form.value.categoryId) {
  //   alert("请选择课程类别");
  //   return;
  // }
  // teachername 现在是可选字段，不做必填验证
  // if (!form.value.teachername.trim()) {
  //   alert("上课老师姓名不能为空");
  //   return;
  // }
  if (!form.value.startTime) {
    alert("请选择开始时间");
    return;
  }
  // body 对应数据库字段，原为description
  if (!form.value.body.trim()) {
    alert("课程介绍不能为空");
    return;
  }

  try {
    submitting.value = true;

    // 准备提交的数据，匹配数据库表结构
    const courseData = {
      title: form.value.title,
      body: form.value.body, // 对应数据库字段，原为description
      teachername: form.value.teachername, // 对应数据库字段，原为teacher
      startTime: form.value.startTime,
      endTime: form.value.endTime, // 新增结束时间
      picPaths: form.value.picPaths, // 新增课程图片
      userid: auth.userId, // 对应数据库字段，作者ID
      // 不传递 addedTime，由数据库自动生成
      // 不传递 categoryId，不在数据库表结构中
    };

    try {
      // 调用API添加课程
      const res = await api.addCourse(courseData);
      if (res && res.data.errno === 0) {
        // API调用成功
        console.log("添加课程成功:", res.data.data);
        alert("添加课程成功");
        // 清除本地存储的缓存，确保下次加载时从API获取最新数据
        localStorage.removeItem("localCourses");
        router.push("/courses");
      } else {
        // API返回非成功状态，使用本地模拟
        console.log("API返回非成功状态，使用本地模拟");
        handleLocalAdd(courseData);
      }
    } catch (error) {
      console.log("API调用失败，使用本地模拟:", error.message);
      // API调用失败，使用本地模拟
      handleLocalAdd(courseData);
    }
  } catch (error) {
    console.error("添加过程中出现异常:", error);
    // 兜底处理
    alert("添加课程失败，请稍后重试");
  } finally {
    submitting.value = false;
  }
};

// 处理本地添加逻辑
const handleLocalAdd = (courseData) => {
  // 获取本地存储的课程数据
  let localCourses = JSON.parse(localStorage.getItem("localCourses") || "[]");

  // 添加新课程
  localCourses.push(courseData);

  // 保存回本地存储
  localStorage.setItem("localCourses", JSON.stringify(localCourses));

  console.log("模拟添加课程成功:", courseData);
  alert("添加课程成功");
  router.push("/courses");
};

// 页面加载时获取课程类别
onMounted(() => {
  loadCategories();
});
</script>